package com.ruoyi.boat.udp;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Objects;

@Slf4j
//@Service("udpSimpleClient") // 有需要再打开
public class UdpSimpleClient {

    @Value("${udp.clients.hosts}")
    private String[] hosts;

    @Value("${udp.clients.port}")
    private Integer port;

    DatagramSocket datagramSocket;

    public void sendMessage(String message, String host, Integer port) {
        if (Objects.isNull(datagramSocket)) {
            try {
                datagramSocket = new DatagramSocket();
            } catch (SocketException e) {
                throw new RuntimeException(e);
            }
        }

        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        byte[] udpMessage = message.getBytes();

        DatagramPacket datagramPacket = new DatagramPacket(udpMessage, udpMessage.length, inetSocketAddress);

        try {
            datagramSocket.send(datagramPacket);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public void sendAll(String message) {
        for (String host : hosts) {
            sendMessage(message, host, port);
        }
    }
}